package com.lee.nio.channel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * NIOFileChannel01
 * 写文件
 *
 * @author dralee
 * @date 2021-12-28 23:02:20
 **/
public class NIOFileChannel01 {
    public static void main(String[] args) throws IOException {
        String str = "hello,File Channel";
        // 创建一个输出流
        FileOutputStream outputStream = new FileOutputStream("file1.txt");
        // 通过outputStream获取对应FileChannel
        // 这个fileChannel真实类型是FileChannelImpl
        FileChannel fileChannel = outputStream.getChannel();
        // 创建一个缓冲区 ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 将src写入到byteBuffer
        byteBuffer.put(str.getBytes(StandardCharsets.UTF_8));
        // 对byteBuffer 进行flip
        byteBuffer.flip();
        // 将byteBuffer数据写入到fileChannel
        fileChannel.write(byteBuffer);
        outputStream.close();

    }
}
